import socket

import time
from Common import sql_content


class _Register(object):

    def __init__(self):
        self.sql_content = sql_content.sql_content()
        self.loginName = ''
        self.password = ''
        self.email = ''

    def _register(self,username_form,password_form,email_form):
        print('_register——.py', username_form, password_form,email_form)
        self.loginName = username_form
        self.password = password_form
        self.email = email_form
        print('_register——.py-self', self.loginName, self.password, self.email)
        if(self.loginName is None or self.password is None or self.email is None):
            return -1   #信息错误
        else:
            __selectByName = self.selectByName()
            print('this len',len(__selectByName))
            if len(__selectByName)!=0:
                return 0    #用户名已存在
            elif len(__selectByName)==0:
                if(self.instert() == 1):
                    return 1    #注册成功
                else:
                    return -1.1
            else:
                return -2   #补充错误码

    def selectByName(self):
        con = self.sql_content.conten()
        sql_login = "select LoginName from logins WHERE LoginName='%s'"%(self.loginName)
        cursor = con.cursor()
        try:
            cursor.execute(sql_login)
            rs = cursor.fetchall()
            print('this is rs',rs)
        except Exception as e:
            print(e)
            # 回滚
            con.rollback()
        cursor.close()
        con.close()

        return rs

    def instert(self):
        Now_Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        #Now_Time = time.localtime(time.time())
        Now_Ip = socket.gethostbyname(socket.gethostname())
        con = self.sql_content.conten()
        sql_login = "insert into logins(LoginName, Password, Email, LoginTime, RegisterDateTime, RegisterIp, LastLoginDateTime, LastLoginIp) " \
                    "value('%s', '%s', '%s', %d, '%s' , '%s', '%s', '%s')" % (
            self.loginName, self.password, self.email, 0, Now_Time, Now_Ip, Now_Time, Now_Ip)
        cursor = con.cursor()
        try:
            cursor.execute(sql_login)
            con.commit()
            rowcount = cursor.rowcount
            print(rowcount)
        except Exception as e:
            print(e)
            # 回滚
            con.rollback()
        cursor.close()
        con.close()

        return rowcount



